﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TouristAgencyDBConnection
{
    public class ReservationsDAO
    {
        private TouristAgencyDataContext context = new TouristAgencyDataContext();

        public void CreateReservation(int tourId, decimal totalPrice, string additionalNotes = null, decimal paidSoFar = 0)
        {
            Reservation reservation = new Reservation();
            reservation.TourID = tourId;
            reservation.TotalPrice = totalPrice;
            reservation.AdditionalNotes = additionalNotes;
            reservation.PaidSoFar = paidSoFar;
            context.Reservations.InsertOnSubmit(reservation);
            context.SubmitChanges();
        }

        public void DeleteReservation(Reservation reservation)
        {
            IEnumerable<People> people = (from p in context.Peoples
                                          join r in context.ReservationsToPeoples
                                          on p.PersonID equals r.PersonID
                                          where r.ReservationID==reservation.ReservationID
                                          select p).ToList<People>();
            IEnumerable<ReservationsToPeople> links = (from link in context.ReservationsToPeoples
                                                       where link.ReservationID == reservation.ReservationID
                                                       select link).ToList<ReservationsToPeople>();
            context.ReservationsToPeoples.DeleteAllOnSubmit(links);
            context.SubmitChanges();
            context.Peoples.DeleteAllOnSubmit(people);
            context.Reservations.DeleteOnSubmit(reservation);
            context.SubmitChanges();
        }

        public void ModifyReservation(Reservation r, int? tourId = null, decimal? totalPrice = null, string additionalNotes = null, decimal? paidSoFar = null)
        {
            if (tourId != null)
            {
                r.TourID = (int)tourId;
            }
            if (totalPrice != null)
            {
                r.TotalPrice = (decimal)totalPrice;
            }
            if (additionalNotes != null)
            {
                r.AdditionalNotes = additionalNotes;
            }
            if (paidSoFar != null)
            {
                r.PaidSoFar = (decimal)paidSoFar;
            }
            context.SubmitChanges();
        }


        public Reservation FindReservation(string reservationUniqueReference)
        {
            Reservation reservation = (from r in context.Reservations
                                       where r.ReservationUniqueReference == reservationUniqueReference
                                       select r).FirstOrDefault<Reservation>();
            return reservation;
        }

    }
}
